<?php

/* 
 * 供销海外购的接口
 * @author wyb
 */
namespace Qwadmin\Model;
use Think\Upload\Driver\Bcs\BCS_RequestCore;
if (! defined ( 'BCS_API_PATH' )) {
	//define ( 'BCS_API_PATH', dirname ( __FILE__ ) );
	define('BCS_API_PATH','D://phpStudy/www/ThinkPHP/Library/Think/Upload/Driver/Bcs');
	}
require_once (BCS_API_PATH . '/requestcore.class.php');

class GxhwApiModel extends ApiModel {
    
    public $prikey="-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALlHWuj/AQohCHDq
CkhLgjSTWLV300n4AVXINvOIwnhXkMNKWJ9uNXbg0PUaKzmI/AEGIOxDl3lIXXyS
8saVZCSDkdwZNUvMkw2ECq8Q9m4EkL+ShY0y8mQTGFEReSe0/62Eq+8U5QB374XD
+9h4Yk8KYZyYaybFpJkSB7k30WsHAgMBAAECgYAICCDXwt4vqzjrdCnX8nYFg3Gw
BC7DoR2ls1U2f3I2t00OOjXXS3bD3YERbv36s4aBINvigheZ6VosIU6m7yj1HVRu
sD4wPE2sFeW9ZSvZea2KaFLSlh7pPoOm926IG0upyBkJ5OKaIWASnRLyVEa15QL/
zpwp8oEiKcA6h9PUsQJBAOop1ZV12lS52n/7aye3fFWY/u/BcWYkvCtYWSp+7eY8
H4ipbeFjJ7yNh9gGl1vRQz2+Mf7FAc/7cDjQ+0oSQ6kCQQDKjoAZ4XYcCRovPNWJ
E9BLqoVyREB6wlv+vK5dmzPJMqb3Vx4tmvxTvS7th44igpz9fK+RocTX08+moJhC
DmcvAkEA0eccQTT6uLY9CjpabKjKuIRECrExsKk/T++LRk+ve5HrhnqyN7bFePy5
h8koxrKH/wHOGR2KKWCv0Q5sI5LJuQJBAJ4E82y9Vj3i3/mQFOoeefY9rmOJWWAr
dkdRfRnrdUf16wm0fgeIDGdrhEur37eOe9jJR9JuCDlztWBBkuadg+MCQGnPFR0k
YDXC6Z6smDyE9EMsvyPmow9S2/NG7p6ax/kVx39WyYwIU06uTE78xCGG/5Rhq3SV
n73/RPz3vgtYmAA=
-----END PRIVATE KEY-----
";
	public $public_key ="-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5R1ro/wEKIQhw6gpIS4I0k1i1
d9NJ+AFVyDbziMJ4V5DDSlifbjV24ND1Gis5iPwBBiDsQ5d5SF18kvLGlWQkg5Hc
GTVLzJMNhAqvEPZuBJC/koWNMvJkExhREXkntP+thKvvFOUAd++Fw/vYeGJPCmGc
mGsmxaSZEge5N9FrBwIDAQAB
-----END PUBLIC KEY-----
";   
	
	//自动组合入库数据
     public function getcatlist($indata)
	 {
		 
		 echo "run getcatlist !====".$indata;
	 }
	 
	 public function test()
	 {
		 
		 echo "test";
		 
	 }
	 
	 function getgoods($indata)
	 {
		  $d['_mt']="commentGoods.findCommentInfoList";
		  $d['itemId']="10478";
		  $d['type']="0";
		  $d['pageSize']="1";
		  $d['pageNum']="15";
		  $d['_sm']="15";
		  $d['_aid']="601";
		  //$d['merchantId']='SFHT';
		  //$d['_tpid']='10233';
		  $data_assemble= $this->assemble($d)."<br>";
		  echo "assembled:".$data_assemble;
		  echo "md5:".md5(base64_encode($data_assemble))."<br><br>";
		  echo "正确的为:a5fcaa0c849fe855d4ab5250f7356360"."<br><br>";
		  
		  $result=file_get_contents("http://www.coopoverseasbuy.com/m.api?_mt=commentGoods.findCommentInfoList&itemId=10478&type=0&pageSize=1&pageNum=15&_sm=md5&_aid=601&_sig=a5fcaa0c849fe855d4ab5250f7356360");
		 // $result=file_get_contents("http://www.coopoverseasbuy.com/m.api?_mt=commentGoods.findCommentInfoList&itemId=10478&type=0&pageSize=2&pageNum=15&_sm=md5&_aid=601&_sig=619143e4f20fdeb0c3800d09501ba05b");
		  var_dump($result);
		  die();
		  $prikey=$this->prikey;
		  $public_key=$this->public_key;
		  $opt['url']=$this->url;
		  
		 // $data="_cb=fengqujsonpcallback&_mt=orderOpenApi.getProuctInfoByItemId&_tpid=10233&_sm=md5&itemId=101&merchantId=GXS_SHG&_sig=4d6288ccc10feb713100de1fbc523bb5&_t=1474705158529" ;
		  $data['_ft']='json';
		  $data['_vc']='1';
		  //$data['_t']=time();
		  
		  $data['_mt']='orderOpenApi.getProuctInfoByItemId';
		  $data['_tpid']='10233';
		  $data['_sm']='rsa';
		  $data['itemId']='101';
		  $data['merchantId']='GXS_SHG';
		  print_r( $data );
		  $data_assemble= $this->assemble($data)."<br>";
		  
		  echo "assembled:".$data_assemble;
		  
		  
		  $encrypted = "";
		  $decrypted = "";  
		  $pri_key=openssl_get_privatekey($prikey);
		  #$pri_key=createPrivateKeyPemResource($prikey);
		  #$pri_key = openssl_pkey_get_private("file:///F://source/rsa_private_key.pem");

		  $pu_key =openssl_pkey_get_public($public_key);
		  var_dump($pri_key);
		  //print_r($pu_key);
		  
		  if($data['_sm']=='md5')
		  {
			 $data['_sig']=base64_encode(md5($data_assemble));  
		  }else
		  {
			  # openssl_private_encrypt($data_assemble,$encrypted,$pri_key,OPENSSL_ALGO_SHA1);
			  # echo "<br>====1:".base64_encode($encrypted);
			   openssl_sign($data_assemble, $encrypted, $pri_key,"sha1WithRSAEncryption");
			   $ok = openssl_verify($data_assemble, $encrypted, $pu_key, "sha1WithRSAEncryption");
			   
			   echo "<br>".$ok."<br>";
			   echo "<br>====1:".base64_encode($encrypted);
			   

			   	openssl_sign($data_assemble, $encrypted, $pri_key,"sha1WithRSAEncryption");
			   $ok = openssl_verify($data_assemble, $encrypted, $pu_key, "sha1WithRSAEncryption");
			   
			   echo "<br>".$ok."<br>";
			   echo "<br>====2:".base64_encode($encrypted);
			  $sig=base64_encode($encrypted);
			  
			  echo "<br>encrypted-->:".$sig."<br>";
			  $data['_sig']=urlencode($sig);
		  }	  

		
		  echo "<br>";
		  $queryurl="http://".$opt['url']."?".http_build_query($data);
		  $result = file_get_contents($queryurl);
		 
		  echo "<br>";
		  echo $queryurl;
		  echo "<br>";
		  echo "<br>encrypted-->:".base64_encode($encrypted)."<br>";
		    var_dump($result);
		  
		  $request = new BCS_RequestCore($queryurl);
		  echo "mothod:".$request->method;
		  //$request->set_body(http_build_query($data));
		  $result=$request->send_request ();
		  var_dump($result);
		  
		   $fenqu= fengquClass::getInstance();
		   $param = array(
            "merchantId"=>'GXS_SHG',
            "itemId"=>'101',
        );
        $url = $fenqu->getUrl('orderOpenApi.getProuctInfoByItemId',$param);
		echo $url;
        $result = file_get_contents($url);
        $jsonResult = json_decode($result);
		print_r($jsonResult->stat->code."<br>") ;
		var_dump($jsonResult);
		 
	 }
	 
	 
	    public function assemble($params) { 
  if (!is_array($params)) 
      return null; 
    ksort($params, SORT_STRING); 
    $sign = ''; 
    foreach ($params AS $key => $val) { 
        $sign .= $key. "=".(is_array($val) ? assemble($val) : urlencode($val)); 
   } 
    echo "<br>";
	echo "assembled:".$sign;
	echo "<br>";
   return $sign; 
   } 
}


class fengquClass{

    private $_config;
    private $_privateKeyResource;

    private static $_instance;

    /**
     * 方法功能：供类内部使用不向往提供功能能
     * 追加描述：实例化当前类
     */
    private function __construct()
    {
        $this->loadConfig();
    }

    /**
     * 方法功能：供类内部使用不向往提供功能能
     * 追加描述：私有克隆方法
     */
    private function __clone(){}

    /**
     * 方法功能：供类内部使用不向往提供功能能
     * 追加描述：初始化配置信息
     */
    private function loadConfig()
    {
        $this->_config = require_once(dirname(__FILE__).'/config.php');
        $this->_privateKeyResource =  $this->createPrivateKeyPemResource($this->_config['rsaPrivateKey']);
    }

	public function createPrivateKeyPemResource($key)
	{
		
		return openssl_get_privatekey($key);
	}
    /**
     * 方法功能：供类内部使用不向往提供功能能
     * 追加描述：返回唯一实例
     * @return output
     */
	 
    public static function getInstance()
    {
        if(!(self::$_instance instanceof self)){
            self::$_instance = new self();
        }
        return self::$_instance;
    }


    /**
     * rsa加密
     * @param $string
     * @return string
     */
    public function encode($string)
    {
       var_dump($this->_privateKeyResource);   
    	echo "<br>";
		echo "before encode:".$string;
		echo "<br>";   
    	openssl_sign($string, $signature, $this->_privateKeyResource,"sha1WithRSAEncryption");
        $result = base64_encode($signature);
		echo "<br>";
		echo "after encode:".$result;
		echo "<br>";   
        return $result;
    }

    /**
     * 生成签名
     * @param $paramArray
     * @return string
     */
    public function makeSignature($paramArray)
    {
        ksort($paramArray);
        $encryptString = '';
        foreach($paramArray as $key=>$value)
        {
            $encryptString = $encryptString.$key."=".$value;
        }
		echo "<br>";
		
		echo "assembled:".$encryptString;
		echo "<br>";
        $signature = $this->encode($encryptString);
        return $signature;
    }

    /**
     * 生成对应操作url
     * @param $operation
     * @param $paramArray
     * @return string
     */
    public function getUrl($operation,$param)
    {
        $paramArray = array(
            "_ft"=>'json',
            "_vc"=>'1',
            "_mt"=>$operation,
            "_sm"=>'rsa',
            "_tpid"=>$this->_config['thirdPartyId'],
        );
        $paramArray = $paramArray + $param;

        //生成签名
		print_r($paramArray);
        $signature = $this->makeSignature($paramArray);

        //生成url
        ksort($paramArray);
        $queryString = '';
        foreach($paramArray as $key=>$value)
        {
            if($queryString == '')
            {
                $queryString = $key."=".urlencode($value);
            }
            else
            {
                $queryString = $queryString."&".$key."=".urlencode($value);
            }
        }
        $url = $this->_config['url'].'?'.$queryString."&_sig=".urlencode($signature);
        return $url;
    }


    /**
     * 从海淘系统获取列表信息
     * @param $startDate
     * @param $endDate
     */
    public function getOrderList($startDate,$endDate)
    {
        $param = array(
            "merchantId"=>$this->_config['merchantId'],
            "startDate"=>$startDate,
            "endDate"=>$endDate,
            "orderState"=>'WAIT_STOCKIN',
        );
        $url = $this->getUrl('twsOpenApi.getOrderList',$param);
        $result = file_get_contents($url);
        $jsonResult = json_decode($result);
        if(isset($jsonResult->stat->code) && $jsonResult->stat->code == 0 && isset($jsonResult->stat->stateList[0]->code) && $jsonResult->stat->stateList[0]->code == 0)
        {
            if(isset($jsonResult->content[0]->orderList) && !empty($jsonResult->content[0]->orderList))
            {
                return $jsonResult->content[0]->orderList;
            }
            else
            {
                return true;
            }
        }
        else
        {
            return false;
        }
    }

}
